<script setup lang="ts">
import type { InterviewQuestionsForm } from '@/models/InterviewQuestions/InterviewQuestionsForm'
import type { FormInstance } from 'ant-design-vue'
import { reactive, ref, watch } from 'vue'
import type { useClassification } from './hooks/useClassification'
import { useSecondaryClassification } from './hooks/useSecondaryClassification'
// @ts-ignore
import Editor from '@toast-ui/editor'
import codeSyntaxHighlight from '@toast-ui/editor-plugin-code-syntax-highlight'
import Prism from 'prismjs'
import { onMounted, onUnmounted } from 'vue'

export interface QuestionEditorProps {
  useClassificationInstance: ReturnType<typeof useClassification>
  editorId: string
  disabledClass: boolean
}

const props = withDefaults(defineProps<QuestionEditorProps>(), {
  disabledClass: false,
})

const useSecondaryClassificationInstance = useSecondaryClassification(
  props.useClassificationInstance,
)

const formRef = ref<FormInstance>()
const formState = reactive<Partial<InterviewQuestionsForm>>({
  title: '',
  answer: '',
  classification: '',
  secondaryClassification: '',
})

async function getFormState(): Promise<Partial<InterviewQuestionsForm> | null> {
  try {
    await formRef.value?.validate()
  } catch (error) {
    return null
  }
  let answer = ''
  if (editor) {
    answer = editor.getMarkdown()
  }
  return { ...formState, answer }
}

function resetFormStata() {
  formState.title = ''
  formState.answer = ''
  formState.classification = ''
  formState.secondaryClassification = ''
  if (editor) {
    editor.setMarkdown('', false)
  }
}

function setFormStata(formData: Partial<InterviewQuestionsForm>) {
  formState.title = formData.title
  formState.answer = formData.answer
  formState.classification = formData.classification
  formState.secondaryClassification = formData.secondaryClassification
  if (editor) {
    editor.setMarkdown(formData.answer, false)
  }
}

defineExpose({
  getFormState,
  setFormStata,
  resetFormStata,
})

watch(
  () => formState.classification,
  () => {
    useSecondaryClassificationInstance
      .changeSecondaryClassificationList(formState.classification)
      .then(() => {
        if (
          useSecondaryClassificationInstance.secondaryClassificatList.value.some(
            (item) => item.code === formState.secondaryClassification,
          )
        ) {
          return
        }
        formState.secondaryClassification = ''
      })
  },
)

let editor: any
function initEditor() {
  editor = new Editor({
    el: document.querySelector(`#${props.editorId}`),
    height: 'auto',
    initialEditType: 'markdown',
    // initialEditType: 'wysiwyg',
    previewStyle: 'tab',
    language: 'zh-CN',
    plugins: [[codeSyntaxHighlight, { highlighter: Prism }]],
  })
}

onMounted(initEditor)
onUnmounted(() => {
  if (!editor) return
  editor.destroy()
})
</script>

<template>
  <div>
    <AForm ref="formRef" :model="formState" autocomplete="off">
      <ARow :gutter="16">
        <ACol :span="6">
          <AFormItem label="一级分类" name="classification">
            <ASelect
              :disabled="props.disabledClass"
              :loading="useClassificationInstance.loadingClassificationList.value"
              v-model:value="formState.classification"
              allow-clear
            >
              <template
                v-for="item of useClassificationInstance.classificationList.value"
                :key="item.id"
              >
                <ASelectOption :value="item.code">{{ item.value }}</ASelectOption>
              </template>
            </ASelect>
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem label="二级分类" name="secondaryClassification">
            <ASelect
              :disabled="props.disabledClass"
              :loading="useSecondaryClassificationInstance.loadingSecondaryClassificatList.value"
              v-model:value="formState.secondaryClassification"
              allow-clear
            >
              <template
                v-for="item of useSecondaryClassificationInstance.secondaryClassificatList.value"
                :key="item.id"
              >
                <ASelectOption :value="item.code">{{ item.value }}</ASelectOption>
              </template>
            </ASelect>
          </AFormItem>
        </ACol>
      </ARow>
      <ARow>
        <ACol :span="24">
          <AFormItem
            :labelCol="{ span: 24 }"
            :wrapperCol="{ span: 24 }"
            label="题目"
            name="title"
            :rules="[
              { required: true, trigger: 'blur' },
              { max: 2000, trigger: 'blur' },
            ]"
          >
            <ATextarea
              v-model:value="formState.title"
              :rows="3"
              :auto-size="{ minRows: 3, maxRows: 5 }"
              show-count
              :maxlength="2000"
            />
          </AFormItem>
        </ACol>
      </ARow>
      <ARow>
        <ACol :span="24">
          <AFormItem
            :labelCol="{ span: 24 }"
            :wrapperCol="{ span: 24 }"
            label="答案"
            :rules="[{ required: true }]"
          >
            <div :id="props.editorId"></div>
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
  </div>
</template>
